<template>
    <div class="ct-bodySet">
        <el-container>
            <el-header class="bgclr-dk-sp0 mb20 headerCoster" >
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/mainPage/welcome' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>角色权限管理</el-breadcrumb-item>
                    <el-breadcrumb-item><span class="main-Clr-ft">角色用户关联</span></el-breadcrumb-item>
                </el-breadcrumb>

            </el-header>

            <el-container class="pl20 pr20" style="display: flex">
                <el-card class="mr15 cardMinWidth autoHeight">
                    <div slot="header" class="">
                        <span>角色列表</span>
                    </div>
                    <el-tree :data="roleTreeData"
                             ref="roleTreeData"
                             :props="roleTreeDataProps"
                             :expand-on-click-node="false"
                             default-expand-all
                             :highlight-current="true"
                             node-key="id"
                             @node-click="clickNode">
                        <span slot-scope="{ node, data }">
                            <span class="labelstyleTree tx-Elps" :title="node.label" >{{ node.label }}</span>
                        </span>
                    </el-tree>
                </el-card>

                <el-card class="cardWidth autoHeight" style="flex:1">
                    <div slot="header">
                        <span>
                            <span class="main-Clr-ft mr2">{{roleName}}</span>
                            用户列表
                        </span>
                    </div>
                    <el-form :inline="true" :model="formData" ref="formData">
                        <el-form-item label="账号:" prop="accountValue">
                            <el-input v-model.trim="formData.accountValue" placeholder="搜索账号..." size="small" class="inputWidth"></el-input>
                        </el-form-item>
                        <el-form-item label="用户名:" prop="userName">
                            <el-input v-model.trim="formData.userName" placeholder="搜索用户名..." size="small" class="inputWidth"></el-input>
                        </el-form-item>
                        <el-form-item class="fltRt">
                            <el-button @click="resetForm('formData')" size="small" class="bkmgColor">重置</el-button>
                        </el-form-item>
                        <el-form-item class="fltRt">
                            <el-button type="primary" size="small" @click="query()" class="mr5">查询</el-button>
                        </el-form-item>
                    </el-form>
                    <el-button-group class="mb10">
                        <el-button size="small" @click="selectAll(getPageData())">全选</el-button>
                        <el-button @click="selectOther(getPageData())" size="small">反选</el-button>
                        <el-dropdown>
                            <el-button size="small" style="border-left-color: #dcdfe6;">
                                更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown" size="small">
                                <el-dropdown-item @click.native = 'batchDelete'>批量删除</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </el-button-group>
                    <el-button type="text" icon="iconfont icon-tianjia" @click="addOneLine" size="small" class="fltRt">添加</el-button>
                    <el-table
                            ref="multipleTable"
                            :data="getPageData()"
                            tooltip-effect="dark"
                            border
                            stripe
                            height="335"
                            :header-cell-style="getRowClass"
                            @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="accountName" label="账号" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="userName" label="用户名" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="enable" label="状态" width="100" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span v-if="scope.row.enable=='1'">启用</span>
                                <span v-bind:style="{color:'red'}" v-else>禁用</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="emailAddress" label="邮箱地址" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="updateDate" label="操作时间" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column label="操作" width="50" show-overflow-tooltip align="center">
                            <template slot-scope="scope">
                                <el-button
                                        title="删除"
                                        @click="deleteRow(scope.$index, scope.row)"
                                        class="deleteButtonColor"
                                        type="text"
                                        icon="iconfont icon-shanchu"
                                        size="small">
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="textAlignRight mt30">
                        <el-pagination
                                layout="total,sizes,prev, pager, next,jumper"
                                @size-change="handleSizeChange"
                                :total="tableData.length"
                                :current-page.sync="currentPage"
                                :page-sizes="[5,10,15,20]"
                                :page-size="pagesize">
                        </el-pagination>
                    </div>
                </el-card>
            </el-container>
            <div class="bottomLayoutBus"></div>
        </el-container>
    </div>

</template>

<script>
    import urlConfig from '../../../config/url.json';
    import Vue from 'vue';
    import { Message } from 'element-ui';

    Vue.component(Message.name, Message);

    let role_ref_userInListUrl = urlConfig.role_ref_userInList;            //角色-用户相关接口         查询角色-用户关联(已关联)
    let role_ref_userUrl = urlConfig.role_ref_user;                        //角色-用户相关接口          增加/删除角色-用户关联
    let roleUrl = urlConfig.roleManage;                                    //角色管理相关接口

    export default {
        data() {
            return {
                selectFlag:true,
                selectData:{},
                roleId:'',
                roleName:'',
                currentPage:1,
                pagesize:5,
                moreOreration: '',                                //更多操作
                userNamesFail:[],                               //多选时的账号--失败
                formData:{
                    accountValue:'',                           //搜索框的值
                    userName:'',                         //状态
                },
                roleTreeData: [],
                roleTreeDataProps: {
                    children: 'children',
                    label: 'roleName'
                },
                tableData: [],                        //显示的表格内容      状态:1.启用,2.禁用
                multipleSelection: [],
                routerParams:{},
                routFlag:true

            }
        },
        methods:{

            //分页后的显示数据
            getPageData(){
                let that=this;
                return that.tableData.slice((that.currentPage-1)*that.pagesize,that.currentPage*that.pagesize);
            },
            
            //批量删除
            batchDelete(){
                let that=this;
                // let role_ref_userUrl = urlConfig.role_ref_user;                      //角色-用户相关接口          增加/删除角色-用户关联
                let selectedTableValue=that.multipleSelection;
                if(selectedTableValue.length>0){
                    let userIdList=[];
                    let userNamesSuccess=[];
                    for(let i=0;i<selectedTableValue.length;i++){
                        userIdList.push(selectedTableValue[i].id)
                        userNamesSuccess.push(selectedTableValue[i].name);
                    }
                    this.$confirm('此操作将批量删除<span class="main-Clr-ft">'+ that.roleName +'</span>角色的用户, 是否继续?', '警告', {
                        dangerouslyUseHTMLString: true,                                   //是否将 message 属性作为 HTML 片段处理
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        const loading = this.$loading({
                            lock: true,
                            text: 'Loading',
                            spinner: 'el-icon-loading',
                        });
                        this.$http({
                            method: 'delete',
                            url: role_ref_userUrl,
                            baseURL:'/api',
                            data: {
                                roleId : that.roleId,
                                userIdList : userIdList
                            }
                        }).then(function(response){
                            if(response.data.code==200) {
                                Message.success('删除   '+ that.roleName +' 用户的权限成功');
                                that.getRoleUserList(that.roleId);
                            }else{
                                Message.error('删除   '+ that.roleName +' 用户的权限失败');
                            }
                            loading.close();
                        }).catch(function(err){
                            Message.error('删除   '+ that.roleName +' 用户的权限失败');
                            console.log(err);
                            loading.close();
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            dangerouslyUseHTMLString: true,
                            message: '已取消删除'+ that.roleName +'</span>权限'
                        });
                    });

                }else{
                    Message.warning('请选择用户');
                }

            },


            //获取角色的用户列表
            getRoleUserList(id){
                debugger;
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                this.$http({
                    method: 'get',
                    url: role_ref_userInListUrl,
                    baseURL:'/api',
                    params: {
                        roleId : id,
                    }
                }).then(function(response){
                    if(response.data.code==200) {
                        if(!response.data.data){
                            return;

                        }else{
                            that.tableData=response.data.data.msUsers;
                        }
                        that.tableData=response.data.data.msUsers;
                    }else{
                        Message.error('查询失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('查询失败');
                    loading.close();
                });
            },

            //点击树节点
            clickNode(data){
                debugger;
                let that=this;
                this.$refs['formData'].resetFields();
                that.roleId=data.id;
                that.roleName=data.roleName;
                that.getRoleUserList(data.id);

            },


            //当选择项(每页显示条数)发生变化时会触发该事件
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },


            //全选
            selectAll(rows){
                rows.forEach(row=>{
                    //toggleAllSelection   用于多选表格，切换所有行的选中状态
                    this.$refs.multipleTable.toggleAllSelection(row);
                });
            },


            //反选
            selectOther(rows){
                rows.forEach(row=>{
                    //toggleRowSelection   用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            },


            //查询
            query(){
                debugger;
                let that=this;
                let paramsData='?roleId='+that.roleId;
                // this.$refs['formData'].resetFields();
                if(that.formData.accountValue.trim().length!=0){
                    paramsData=paramsData+'&accountName='+that.formData.accountValue;
                    if(this.formData.userName.trim().length!=0){
                        paramsData=paramsData+'&userName='+that.formData.userName
                    }else{
                        paramsData=paramsData;
                    }
                }else{
                    if(this.formData.userName){
                        paramsData=paramsData+'&userName='+that.formData.userName
                    }else{
                        paramsData=paramsData;
                    }
                }
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                this.$http({
                    method: 'get',
                    url: role_ref_userInListUrl + paramsData,
                    baseURL:'/api'
                }).then(function(response){
                    if(response.data.code==200) {
                        if(!response.data.data){
                            return;
                        }
                        that.tableData=response.data.data.msUsers;
                    }else{
                        Message.error('查询失败');
                    }
                    loading.close();
                }).catch(function(err){
                    Message.error('查询失败');
                    console.log(err);
                    loading.close();
                });
            },


            //重置   根据重置后的条件重新查询
            resetForm(formName) {
                this.$refs[formName].resetFields();

                let that=this;
                that.getRoleUserList(that.roleId);
            },


            //添加--其实是跳转
            addOneLine(){
                this.$router.push({
                    path:'/mainPage/userRefRoleManageSpAddUserToRoles',
                    query: {
                        roleId: this.roleId,
                        roleName: this.roleName,
                    }
                })
            },


            //设置表头颜色
            getRowClass({ rowIndex }) {
                if (rowIndex == 0) {
                    return 'background:#F5F7FA'
                } else {
                    return ''
                }
            },


            //选择每页显示数据条数
            handleSizeChange(val) {
                this.pagesize=val;
            },


            // 删除/移除一行          上面还有批量删除方法，一起改
            deleteRow(index,row) {
                let that=this;
                this.$confirm('是否删除    <span class="main-Clr-ft">'+ row.userName   +'</span>的<span class="main-Clr-ft">'+ this.roleName +'</span>权限?', '警告', {
                    dangerouslyUseHTMLString: true,                                   //是否将 message 属性作为 HTML 片段处理
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                }).then(() => {
                    let userIdList=[];

                    userIdList.push(row.id);
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                    });
                    this.$http({
                        method: 'delete',
                        url: role_ref_userUrl,
                        baseURL:'/api',
                        data: {
                            roleId : that.roleId,
                            userIdList : userIdList
                        }
                    }).then(function(response){
                        if(response.data.code==200) {
                            that.getRoleUserList(that.roleId);
                            Message.success('删除    '+ row.userName   +'的'+ that.roleName +'权限成功');
                        }else{
                            Message.error('删除    '+ row.userName   +'的'+ that.roleName +'权限失败');
                        }
                        loading.close();
                    }).catch(function(err){
                        Message.error('删除    '+ row.userName   +'的'+ that.roleName +'权限失败');
                        console.log(err);
                        loading.close();
                    });

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        dangerouslyUseHTMLString: true,
                        message: '已取消删除    <span class="main-Clr-ft">'+ row.name   +'</span>的<span class="main-Clr-ft">'+ this.roleName +'</span>权限'
                    });
                });

                // this.$refs.roleTreeData.setCurrentKey(that.roleId);
            },

            //获取角色列表
            getRoleTreeData(){
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                this.$http({                                                 //获取角色列表
                    method: 'get',
                    url: roleUrl,
                    baseURL:'/api'
                }).then(function(response){
                    if(response.data.code==200) {
                        var newdata=response.data.data.roleInfos;
                        that.roleTreeData=that.getJsonTree(newdata,'-1');
                        debugger
                        if(that.routFlag ==false){
                            that.roleId = that.roleTreeData[0].id;
                            that.roleName = that.roleTreeData[0].roleName;
                        }
                    }else{
                        Message.error('获取角色树失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取角色树失败');
                    loading.close();
                })
            },
            getJsonTree(newdata,parentId){
                let that=this;
                var itemArr=[];
                for(var i=0;i<newdata.length;i++){
                    var node=newdata[i];
                    if(node.parentId==parentId ){
                        var newNode={id:node.id,
                            roleName:node.roleName,
                            parentId:node.parentId,
                            description:node.description,
                            createBy:node.createBy,
                            createDate:node.createDate,
                            updateBy:node.updateBy,
                            updateDate:node.updateDate,
                            children:that.getJsonTree(newdata,node.id)};
                        itemArr.push(newNode);
                    }
                }
                return itemArr;
            },
            getParams:function(){
                debugger;
                let that=this;
                // 取到路由带过来的参数
                that.routerParams = that.$route.query;
                if(Object.keys(that.routerParams).length==0){
                    that.routFlag = false;
                }else{
                    that.roleId = that.routerParams.roleId;
                    that.roleName = that.routerParams.roleName;
                }
            },
        },
        created:function(){
            this.getParams();
        },
        watch: {
            // 监测路由变化,只要变化了就调用获取路由参数方法将数据存储本组件即可
            '$route': 'getParams'
        },
        mounted(){
            let that = this;
            //获取角色列表
            that.getRoleTreeData();
        },
        updated(){
            let that = this;
            if(that.selectFlag){
                //1页面加载完成左侧树默认选中超级管理员
                that.$refs.roleTreeData.setCurrentKey(that.roleId);
                that.getRoleUserList(that.roleId);
                that.selectFlag=false;
            }
        }
    }
</script>

<style scoped>
    .inputWidth{
        width: 180px;
    }

    .headerCoster{
        height: 59px;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
    }

    .deleteButtonColor{
        color: red;
    }

    .cardMinWidth{
        min-width: 275px;
    }

    .cardWidth{
        width: 100%;
    }
</style>